package com.contract.commonlib.util

import android.text.TextUtils
import android.preference.PreferenceManager
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat
import android.content.*
import android.graphics.drawable.Drawable
import android.os.*
import android.widget.ImageView
import com.blankj.utilcode.util.Utils
import com.contract.commonlib.BuildConfig
import java.lang.Exception
import java.util.regex.Pattern

object ToolUtils {
    /**
     * @param s
     * @param start include(start with zero)
     * @param end   exclude
     * @return
     */
    fun encryptString(s: String, start: Int, end: Int): String? {
        try {
            val buffer = CharArray(s.length)
            s.toCharArray(buffer, 0, 0, s.length)
            for (i in buffer.indices) {
                if (i >= start && i < end) {
                    buffer[i] = '*'
                }
            }
            return String(buffer)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun isMobileNum(mobiles: String?): Boolean {
        if (mobiles?.isNotBlank() == true) {
            val p = Pattern.compile("^1[0-9]{10}$")
            val m = p.matcher(mobiles)
            return m.matches()
        }
        return false
    }


    fun isFirstIn(c: Context?): Boolean {
        return PreferenceManager.getDefaultSharedPreferences(c).getBoolean(
            "first_in", true
        )
    }

    fun setIsFirstIn(c: Context?, b: Boolean) {
        PreferenceManager.getDefaultSharedPreferences(c).edit()
            .putBoolean("first_in", false).commit()
    }

    fun ifIsPictureMessage(message: String): Boolean {
        return message.startsWith("~^") && message.endsWith("~^")
    }

    fun getPicName(message: String): String? {
        var result: String? = null
        if (message.length > 4) {
            result = message.substring(2, message.length - 2)
            return if (result != null && (result.endsWith(".png") || result.endsWith(".PNG")
                        || result.endsWith(".jpeg")
                        || result.endsWith(".JPEG")
                        || result.endsWith(".jpg") || result.endsWith(".JPG"))
            ) {
                result
            } else {
                null
            }
        }
        return result
    }

    fun isEmail(strEmail: String?): Boolean {
        val strPattern =
            "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"
        val p = Pattern.compile(strPattern)
        val m = p.matcher(strEmail)
        return m.matches()
    }

    //设置图片着色器 tint
    fun setDrawbleTint(context: Context?, drawbleId: Int, color: Int, imageView: ImageView) {
        try {
            val up = ContextCompat.getDrawable(context!!, drawbleId)
            val drawableUp = DrawableCompat.wrap(up!!)
            DrawableCompat.setTint(drawableUp, color)
            imageView.setImageDrawable(drawableUp)
            val up1 = ContextCompat.getDrawable(context, drawbleId)
            val drawableUp1 = DrawableCompat.unwrap<Drawable>(
                up1!!
            )
            DrawableCompat.setTintList(drawableUp1, null)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun hidePhone(phonenum: String): String {
        return if (TextUtils.isEmpty(phonenum)) {
            ""
        } else phonenum.replace("(\\d{3})\\d{4}(\\d{4})".toRegex(), "$1****$2")
    }

    fun getChannel(): String? {
        if ("release" != BuildConfig.BUILD_TYPE) {
            return "1"
        }
        val market = PackerNg.getMarket(Utils.getApp())
        try {
            val info = market.split(",").toTypedArray()
            return info[0]
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }
    fun copyToClip(context: Context, content: String?) {
        runOnMainThread { //获取剪贴板管理器：
            val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            // 创建普通字符型ClipData
            val mClipData = ClipData.newPlainText("Label", content)
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData)
        }
    }

    private fun runOnMainThread(runnable: Runnable) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            runnable.run()
        } else {
            Handler().post(runnable)
        }
    }
}